import paramiko


class SftpUtil:
    def __init__(self, host, user, password, port=22):
        self.host = host
        self.user = user
        self.password = password
        self.port = port

        # transport
        self.t = paramiko.Transport(sock=(self.host, self.port))
        self.t.connect(username=self.user, password=self.password)

        # 链接失败的重试次数
        self.try_times = 3
        self.sftp = self.get_sftp()

    def get_sftp(self):
        sftp = paramiko.SFTPClient.from_transport(self.t)
        return sftp

    def close(self):
        self.t.close()
        self.sftp.close()

    # get单个文件
    def get(self, remotefile, localfile):
        is_success = False
        for i in range(self.try_times):
            try:
                self.sftp.get(remotefile, localfile)
                is_success = True
                break
            except:
                continue
        return is_success

    # put单个文件
    def put(self, localfile, remotefile):
        is_success = False
        for i in range(self.try_times):
            try:
                self.sftp.put(localfile, remotefile)
                is_success = True
                break
            except:
                continue
        return is_success
